<template>
  <div>
    <!--  面包屑导航区域-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--  卡片试图区域-->
    <el-card>
      <!--    搜索区域-->
      <el-row :gutter="15">
        <!--        输入框-->
        <el-col :span="10">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <!--        添加用户-->
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!--      用户列表区域-->
      <el-table :data="userList" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <!-- {{ scope.row }}-->
            <el-switch v-model="scope.row.mg_state" @change="userStatysChange(scope.row)" active-color="#9999cc"
                       inactive-color="#787878"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="描述">
          <template slot-scope="scope">
            <!--    修改按钮-->
            <el-button type="primary" icon="el-icon-edit" circle size="mini"
                       @click="showEditDialog(scope.row.id)"></el-button>
            <!--    删除按钮-->
            <el-button type="danger" icon="el-icon-delete" circle size="mini"
                       @click="deleteUserId(scope.row.id)"></el-button>
            <!--    分配角色按钮-->
            <el-tooltip class="item" effect="dark" content="分配角色" placement="top-start" :enterable="false">
              <el-button type="warning" icon="el-icon-star-off" circle size="mini"
                         @click="setRole(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!--      分页区域-->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :current-page="queryInfo.pagenum" :page-sizes="[1,2,4,6,10]"
                     :page-size="queryInfo.pagesize"
                     layout="total, sizes, prev, pager, next, jumper" :total="totle">
      </el-pagination>
    </el-card>
    <!--    添加用户对话框-->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="closeForm">
      <!--      表单区域-->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!--      底部区域-->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="adduser">确 定</el-button>
      </span>
    </el-dialog>
    <!--    修改用户对话框-->
    <el-dialog title="修改用户" :visible.sync="updataDialogVisible" width="50%" @close="updataDialogClose">
      <el-form :model="updataFrom" :rules="updataFormRules" ref="updataFormRef" label-width="70px">
        <el-form-item label="用户名">
          <el-input v-model="updataFrom.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="updataFrom.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="updataFrom.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="updataDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="updataUserInfo">确 定</el-button>
  </span>
    </el-dialog>
    <!--  分配角色对话框-->
    <el-dialog title="分配角色" :visible.sync="setRoleVisible" width="50%" @close="setRoleVisibleClose">
      <div>
        <p>当前的用户：{{ userInfo.username }}</p>
        <p>当前的角色：{{ userInfo.role_name }}</p>
        <p>分配新角色：
          <el-select v-model="selectRoleId" placeholder="---请选择---">
            <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id"></el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
    <el-button @click="setRoleVisible = false">取 消</el-button>
    <el-button type="primary" @click="setRoleInfo">确 定</el-button>
  </span>
    </el-dialog>
  </div>

</template>

<script>
export default {
  data() {
    // 验证邮箱
    var checkEmail = (rule, value, callback) => {
      const regEmail = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
      if (regEmail.test(value)) {
        return callback()
      }
      callback(new Error('邮箱格式错误！'))
    }
    // 验证邮箱
    var checkMobile = (rule, value, callback) => {
      const regMobile = /^[1][3,4,5,7,8][0-9]{9}$/
      if (regMobile.test(value)) {
        return callback()
      }
      callback(new Error('手机号错误！'))
    }
    return {
      queryInfo: {
        query: '',    //查询参数
        pagenum: 1,   //当前页码
        pagesize: 2   //每页显示条数
      },
      userList: [], //用户数组
      totle: 0,     //条数
      addDialogVisible: false,  //添加控制对话框
      //添加用户数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      //验证规则对象
      addFormRules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 3, max: 16, message: '用户名长度在 3-16 个字符', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 6, max: 16, message: '用户名长度在 6-16 个字符', trigger: 'blur'}
        ],
        email: [
          {required: true, message: '请输入邮箱', trigger: 'blur'},
          {validator: checkEmail, trigger: 'blur'}
        ],
        mobile: [
          {required: true, message: '请输入手机号', trigger: 'blur'},
          {validator: checkMobile, trigger: 'blur'}
        ]
      },
      updataDialogVisible: false, //修改控制对话框
      updataFrom: {},   //储存查到的用户信息
      updataFormRules: {
        email: [
          {required: true, message: '请输入邮箱', trigger: 'blur'},
          {validator: checkEmail, trigger: 'blur'}
        ],
        mobile: [
          {required: true, message: '请输入手机号', trigger: 'blur'},
          {validator: checkMobile, trigger: 'blur'}
        ]
      },
      setRoleVisible: false,  //控制
      userInfo: {},      //需要被分配角色的用户
      roleList: [],        //角色列表
      selectRoleId: {}      //查询到的用户
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    //异步获取用户信息
    async getUserList() {
      const {data: res} = await this.$http.get('users', {params: this.queryInfo})
      if (res.meta.status != 200) {
        this.$message.error('获取数据失败！')
      } else {
        this.userList = res.data.users
        this.totle = res.data.total
      }
    },

    // 每页显示条数 数据改变
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    // 当前页码 数据改变
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    //监听 开关改变
    async userStatysChange(useInfo) {
      console.log(useInfo)
      const {data: res} = await this.$http.put(`users/${useInfo.id}/state/${useInfo.mg_state}`)
      if (res.meta.status != 200) {
        useInfo.mg_state = !useInfo.mg_state
        return this.$message.error('更新用户状态失败！')
      }
      this.$message.success('用户状态更新成功！')
    },
    //监听 对话框改变  重置信息
    closeForm() {
      this.$refs.addFormRef.resetFields()
    },
    // 预验证 添加用户
    adduser() {
      this.$refs.addFormRef.validate(async valid => {
        // console.log(valid)
        const {data: res} = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 201) {
          this.$message.error('添加用户失败！')
        }
        this.$message.success('添加用户成功！')
        //隐藏对话框
        this.addDialogVisible = false
        //刷新列表
        this.getUserList()
      })
    },
    //获取用户信息
    async showEditDialog(id) {
      const {data: res} = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户信息失败！')
      }
      this.updataFrom = res.data
      // console.log(this.updataFrom)
      this.updataDialogVisible = !this.updataDialogVisible
    },
    updataDialogClose() {
      this.$refs.updataFormRef.resetFields()
    },
    //修改用户信息
    updataUserInfo() {
      this.$refs.updataFormRef.validate(async valid => {
        if (!valid) return
        const {data: res} = await this.$http.put('users/' + this.updataFrom.id, {
          email: this.updataFrom.email,
          mobile: this.updataFrom.mobile
        })
        if (res.meta.status !== 200) {
          return this.$message.error('修改用户信息失败！')
        }
        this.updataDialogVisible = false
        this.getUserList()
        this.$message.success('修改用户信息成功！')
      })
    },
    //删除用户
    async deleteUserId(id) {
      const confirmRef = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        center: true,
        type: 'warning',
      }).catch(err => err)

      //确认删除 返回 confirm   取消删除 返回cancel
      if (confirmRef !== 'confirm') {
        return this.$message.info('已取消删除！')
      }
      const {data: res} = await this.$http.delete('users/' + id)
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('删除用户失败！')
      }
      this.$message.success('删除用户成功！')
      this.getUserList()
    },
    // 展示分配角色对话框
    async setRole(userInfo) {
      this.userInfo = userInfo
      const {data: res} = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        this.$message.error('获取角色数据失败！')
      }
      this.roleList = res.data
      console.log(this.roleList)
      this.setRoleVisible = true
    },
    //点击分配角色   预验证
    async setRoleInfo() {
      if (!this.selectRoleId) {
        return this.$message.error('请选择要分配的角色！')
      }
      const {data: res} = await this.$http.put(`users/${this.userInfo.id}/role`, {rid: this.selectRoleId})
      if (res.meta.status !== 200) {
        this.$message.error('更新角色失败！')
      }
      this.$message.success('更新角色成功！')
      this.getUserList()
      this.setRoleVisible = false
    },
    //监听分配角色对话框
    setRoleVisibleClose() {
      this.selectRoleId = ''
      this.userInfo = {}
    }
  }
}
</script>

<style lang="less" scoped>

</style>
